package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.api.dto.ItemDTO;
import com.hmall.api.dto.OrderDetailDTO;
import com.hmall.common.exception.BizIllegalException;
import com.hmall.common.utils.BeanUtils;


import com.hmall.item.domain.po.Item;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.service.IItemService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author 虎哥
 */
@Service
@RequiredArgsConstructor
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Autowired
    private ItemMapper itemMapper;

    @Transactional
    @Override
    public void deductStock(List<OrderDetailDTO> items) {
        //查库存
        for (OrderDetailDTO item : items) {
            Item one = lambdaQuery().eq(Item::getId, item.getItemId()).one();
            if (one.getStock() - item.getNum() < 0) {
                throw new BizIllegalException("库存不足！");
            }
        }
        for (OrderDetailDTO item : items) {

            lambdaUpdate()
                    .eq(Item::getId, item.getItemId())
                    .setSql("stock=stock-" + item.getNum());

        }

    }

    @Override
    public List<ItemDTO> queryItemByIds(Collection<Long> ids) {
        return BeanUtils.copyList(listByIds(ids), ItemDTO.class);
    }
}
